﻿using XW.Utils;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using StackExchange.Exceptional;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using XW.Core;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Http.Extensions;

namespace XW.Web.Framework
{
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            this._next = next;
        }


        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
                if (context.Response.StatusCode == 404)
                {
                    if (context.Request.IsAjaxRequest())
                    {
                        context.Response.StatusCode = 200;
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new { resultCode = ResultCode.Error, message = "请求不存在或没有权限！" }));
                    }
                    else {
                        context.Request.Path = "/Home/Error";
                        await this._next(context);
                    } 
                } 
            }
            catch (Exception ex)
            {
                //当作正常响应，根据header里的errormessage字段判断是否有错
                if (context != null && context.Response!=null && context.Response.StatusCode != 200)
                {
                    context.Response.StatusCode = 200;
                }

                var message = string.Empty;

                /*  if (ex is NoLoginException)
                  {
                      context.Response.ContentType = "application/json; charset=utf-8";
                      await context.Response.WriteAsync(JsonConvert.SerializeObject(new { success = false, msg = ex.Message, login = false }), Encoding.UTF8);
                      return;
                  }
                  else if (ex is NoPermissionException)
                  {
                      context.Response.ContentType = "application/json; charset=utf-8";
                      await context.Response.WriteAsync(JsonConvert.SerializeObject(new { success = false, msg = ex.Message, NoPermission = false }), Encoding.UTF8);
                      return;
                  }
                  else if (ex is CustomException)
                  {
                      message = ex.Message;
                  }

                  else*/
                {
                    try
                    {
                        ex.Log(context, customData: new Dictionary<string, string> { { "cusTace", ex.StackTrace } });
                        message = ex.Message;//CommonHelper.GetExceptionMsg(ex); 
                    }
                    catch (Exception)
                    { 
                    }
                 
                }

                await context.Response.WriteAsync(JsonConvert.SerializeObject(new { resultCode = ResultCode.Error, message = message }));
            }
            finally {
                if (context.Response.StatusCode == 401)
                {
                    
                    if (context.Request.IsAjaxRequest())
                    {
                        context.Response.StatusCode = 200;
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new { resultCode = ResultCode.Unauthorized, message = "请登陆！" }));
                    }
                    else
                    {
                        //var r = context.Request;
                       // //UrlHelper 
                       //string login =  UriHelper.BuildAbsolute(
                       //     r.Scheme,
                       //     r.Host,
                       //     r.PathBase,
                       //    "/Home/Login");
                        //context.Request.
                        context.Response.Redirect("/Home/Login");
                    } 
                }
 
            }

        }
    }

    public static class ExceptionHandlingEx
    {
        public static IApplicationBuilder UseExceptionHandling(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionHandlerMiddleware>();
        }
    }
}
